"""
  Copyright 2008 Texas A&M University Licensed under the
  Educational Community License, Version 2.0 (the "License"); you may
  not use this file except in compliance with the License. You may
  obtain a copy of the License at

  http://www.osedu.org/licenses/ECL-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an "AS IS"
  BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  or implied. See the License for the specific language governing
  permissions and limitations under the License.
"""

import unittest
from StringIO import StringIO
from xml.etree import ElementTree as etree

from meercat.base import Instance, Metadata

from meercat.harvester.sfx.harvester import SfxHarvester

one_object = "JOURNAL OF PHYSICAL CHEMISTRY B CONDENSED MATTER MATERIALS SURFACES INTERFACES BIOPHYSICAL\tThe journal of physical chemistry. B, Condensed matter, materials, surfaces, interfaces & biophysical\t4\t1520-6106\t110994169597000\tAmerican Chemical Society Journals\tAvailable from 1997 volume: 101 issue: 1.\t1520-5207\tTHE JOURNAL OF PHYSICAL CHEMISTRY B CONDENSED MATTER MATERIALS SURFACES INTERFACES AND BIOPHYSICAL-J PHYS CHEM B-JOURNAL OF PHYSICAL CHEMISTRY B\tgetFullTxt\tgarbage\t111032796997000\t856u\t856y\t856a\t245h\tlocal_threshold\t$obj->parsedDate('>=','1997','101','1')\t110974884846159\t110974884846160\t111032796997000\tcategories\tlocal attribute\tisbn\tisbn2\tAmerican Chemical Society\tWashington, D.C.\tyear\tJOURNAL\tACTIVE\tinstitute_id\tinstitute name\tinstitute availability\teng\tanother title"

one_object_metadata = '''<?xml version="1.0" encoding="utf-8"?>
<object>
<title type="sortable">JOURNAL OF PHYSICAL CHEMISTRY B CONDENSED MATTER MATERIALS SURFACES INTERFACES BIOPHYSICAL</title>
<title>The journal of physical chemistry. B, Condensed matter, materials, surfaces, interfaces &amp; biophysical</title>
<non_filing_character>4</non_filing_character>
<identifier type="issn">1520-6106</identifier>
<identifier type="object_id">110994169597000</identifier>
<target_public_name>American Chemical Society Journals</target_public_name>
<threshold>Available from 1997 volume: 101 issue: 1.</threshold>
<identifier type="issn">1520-5207</identifier>
<title type="abbreviated">THE JOURNAL OF PHYSICAL CHEMISTRY B CONDENSED MATTER MATERIALS SURFACES INTERFACES AND BIOPHYSICAL-J PHYS CHEM B-JOURNAL OF PHYSICAL CHEMISTRY B</title>
<target_service_type>getFullTxt</target_service_type>
<identifier type="lccn">garbage</identifier>
<identifier type="object_portfolio">111032796997000</identifier>
<marc field="856u">856u</marc>
<marc field="856y">856y</marc>
<marc field="856a">856a</marc>
<marc field="245h">245h</marc>
<threshold encoding="perl" type="local">local_threshold</threshold>
<threshold encoding="perl" type="global">$obj->parsedDate('&gt;=','1997','101','1')</threshold>
<identifier type="target">110974884846159</identifier>
<identifier type="target_service">110974884846160</identifier>
<identifier type="object_portfolio">111032796997000</identifier>
<categories>categories</categories>
<local_attribute>local attribute</local_attribute>
<identifier type="isbn">isbn</identifier>
<identifier type="isbn">isbn2</identifier>
<publisher>American Chemical Society</publisher>
<publisher_place>Washington, D.C.</publisher_place>
<date type="publication">year</date>
<object_type>JOURNAL</object_type>
<availability>ACTIVE</availability>
<identifier type="institute">institute_id</identifier>
<institute_name>institute name</institute_name>
<availability type="institute">institute availability</availability>
<language>eng</language>
<title type="main">another title</title>
</object>'''

multiple_objects = '''TITLE\ttitle\t\t1111-0000\t110994169597000\tpublic name\tforever\t1111-2222\tabbreviated title\tgetFullTxt\t1234567890\t111032796997000\t\t\t\t\t\tblah\t110974884846159\t110974884846159\t110974884846159\t15 blah;20 blah;\t\t\tMe\tHere\t1001\tJOURNAL\tACTIVE\t\t\t\teng\tmain title\t
TITLE\ttitle\t\t1111-0000\t110994169597000\tpublic name\tforever\t1111-2222\tabbreviated title\tgetFullTxt\t1234567890\t111032796997004\t\t\t\t\t\tblah\t110974884846159\t110974884846159\t110974884846159\t15 blah;20 blah;\t\t\tMe\tHere\t1001\tJOURNAL\tACTIVE\t\t\t\teng\tmain title\t
TITLE\ttitle\t\t1111-0000\t110994169597004\tpublic name\tforever\t1111-2222\tabbreviated title\tgetFullTxt\t1234567890\t111032796997008\t\t\t\t\t\tblah\t110974884846159\t110974884846159\t110974884846159\t15 blah;20 blah;\t\t\tMe\tHere\t1001\tJOURNAL\tACTIVE\t\t\t\teng\tmain title\t'''

class BaseTest(unittest.TestCase):
    _source_function = lambda h: StringIO('')
    _length = 0

    def setUp(self):
        self.harvester = SfxHarvester(source = 'test',
                                      source_function = self._source_function)
        self.instances = self.harvester.harvest()

    def testLength(self):
        self.assertEqual(len(self.instances),self._length)

class MultiInstanceTest(BaseTest):
    _source_function = lambda h: StringIO(multiple_objects)
    _length = 2

    def testInstance1(self):
        i1 = Instance(source='sfx://test',
                      identifier='110994169597000')

        self.assertTrue(i1 in self.instances,
                        '%s not in %s' % (unicode(i1),unicode(self.instances)))

    def testInstance2(self):
        i2 = Instance(source='sfx://test',
                      identifier='110994169597004')
        self.assertTrue(i2 in self.instances,
                        '%s not in %s' % (unicode(i2),unicode(self.instances)))

class MetadataTest(BaseTest):
    _source_function = lambda h: StringIO(one_object)
    _length = 1

    def setUp(self):
        super(MetadataTest,self).setUp()

    def testMetadata(self):
        instance = self.instances[0]
        m = Metadata(source='sfx://test',format='sfx',
                     value=etree.tostring(etree.fromstring(one_object_metadata),
                                          encoding='utf-8').replace('\n','').strip())
        self.assertTrue(m in instance.getMetadata(),
                        "Metadata not found: %s" % (m.getValue()))

def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(MetadataTest))
    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(MultiInstanceTest))
    return suite

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(test_suite())